<?php
/**************************************************************************
 * Naanal PHP Framework, Simple, Efficient and Developer Friendly
 * Ver 3.0, Copyright (C) <2010>  <Tamil Amuthan. R>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/
class ClsLCurl extends ClsNaanalLibrary 
{
    private $arrError=array();
    public function __construct()
    {
        
    }
    public function init()
    {
        
    }
    public function getError()
    {
        return $this->arrError;
    }
    ///replacement of CURLOPT_FOLLOWLOCATION
    public function curl_exec_follow($ch, &$maxredirect = null)
    {
        // we emulate a browser here since some websites detect
        // us as a bot and don't let us do our job
        $user_agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.7.5)".
                      " Gecko/20041107 Firefox/1.0";
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent );

        $mr = $maxredirect === null ? 10 : intval($maxredirect);

        if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {

          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, $mr > 0);
          curl_setopt($ch, CURLOPT_MAXREDIRS, $mr);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
          curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

        } else {

          curl_setopt($ch, CURLOPT_FOLLOWLOCATION, false);

          if ($mr > 0)
          {
            $original_url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
            $newurl = $original_url;

            $rch = curl_copy_handle($ch);

            curl_setopt($rch, CURLOPT_HEADER, true);
            curl_setopt($rch, CURLOPT_NOBODY, true);
            curl_setopt($rch, CURLOPT_FORBID_REUSE, false);
            do
            {
              curl_setopt($rch, CURLOPT_URL, $newurl);
              $header = curl_exec($rch);
              if (curl_errno($rch)) {
                $code = 0;
              } else {
                $code = curl_getinfo($rch, CURLINFO_HTTP_CODE);
                if ($code == 301 || $code == 302) {
                  preg_match('/Location:(.*?)\n/', $header, $matches);
                  $newurl = trim(array_pop($matches));

                  // if no scheme is present then the new url is a
                  // relative path and thus needs some extra care
                  if(!preg_match("/^https?:/i", $newurl)){
                    $newurl = $original_url . $newurl;
                  }   
                } else {
                  $code = 0;
                }
              }
            } while ($code && --$mr);

            curl_close($rch);

            if (!$mr)
            {
              if ($maxredirect === null)
              trigger_error('Too many redirects.', E_USER_WARNING);
              else
              $maxredirect = 0;

              return false;
            }
            curl_setopt($ch, CURLOPT_URL, $newurl);
          }
        }
        return curl_exec($ch);
    }
    function LoadCURLPage($url, $agent='', $cookie='', $referer='', $post_fields='', $ssl = '')
    {
        $ch = curl_init(); 

        curl_setopt($ch, CURLOPT_URL, $url);

        if($ssl) curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,  2);

        curl_setopt ($ch, CURLOPT_HEADER, 0);

        if($agent) curl_setopt($ch, CURLOPT_USERAGENT, $agent);

        if($post_fields)
        {
            curl_setopt($ch, CURLOPT_POST, 1); 
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields); 
        }

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

        if($referer) curl_setopt($ch, CURLOPT_REFERER, $referer);

        if($cookie)
        {
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
        }

        $result = $this->curl_exec_follow($ch);

        $status = curl_getinfo($ch);
        curl_close($ch);

        if($status['http_code']!=200){
            if($status['http_code'] == 301 || $status['http_code'] == 302) {
                list($header) = explode("\r\n\r\n", $result, 2);
                $matches = array();
                preg_match("/(Location:|URI:)[^(\n)]*/", $header, $matches);
                if(!empty($matches))
                {
                    $url = trim(str_replace($matches[1],"",$matches[0]));
                    $url_parsed = parse_url($url);
                    return (isset($url_parsed))? geturl($url, $referer):'';
                }
                return "";
            }
            $oline='';
            foreach($status as $key=>$eline){$oline.='['.$key.']'.$eline.' ';}
            $line =$oline." \r\n ".$url."\r\n-----------------\r\n";
            $this->arrError[]=  str_replace("\r\n", "<br />", $line);
            //$handle = @fopen('./curl.error.log', 'a');
            //fwrite($handle, $line);
            return false;
        }

        return $result;
    }

    function extract_unit($string, $start, $end)  
    {  
        $pos = stripos($string, $start);  

        $str = substr($string, $pos);  

        $str_two = substr($str, strlen($start));  

        $second_pos = stripos($str_two, $end);  

        $str_three = substr($str_two, 0, $second_pos);  

        $unit = trim($str_three); // remove whitespaces  

        return $unit;  
    }
}
?>